package cn.edu.cqupt.cyExam.controller;
import cn.edu.cqupt.cyExam.myBatis.bean.User;
import cn.edu.cqupt.cyExam.myBatis.dao.UserMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@RestController
@CrossOrigin
public class LoginController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/testlogin")
    public String testlogin(){
        return "test success";
    }

    @RequestMapping("/user/login")
    public String login(@RequestParam(value="username",required=false) String username,
                        @RequestParam(value="password",required=false) String password,
                        HttpSession session) throws JsonProcessingException {

        System.out.print(username);
        System.out.print(password);
        User user = userMapper.userLogin(username,password);

        if (user==null){
            return "fail";
        }else {
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(user);
            System.out.print(json);
            session.setAttribute("userMassage",user);
            return json;
        }






// 服务器内部跳转到登录页面



//        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
//            model.addAttribute("msg","用户名和密码不能为空");
//            session.setAttribute("loginUser",username );
//            return "index";
//        }else {
//            return "redirect:/main.html";
//        }

    }

}
